package org.jeecg.modules.monitoring.j_monitoring.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlVirtualizationCluster;
import org.jeecg.modules.monitoring.j_monitoring.utils.EquipmentUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlStorageResources;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlStorageResourcesMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlResourceStorageService;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlStorageResourcesService;
import org.jeecg.modules.monitoring.j_monitoring.service.impl.GatewaySystemFdnServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
* @Description: 存储设备
* @Author: xiaoyq
* @Date:   2023-02-22
* @Version: V1.0
*/
@Api(tags="存储设备")
@RestController
@RequestMapping("/j_monitoring/mGlStorageResources")
@Slf4j
public class MGlStorageResourcesController extends JeecgController<MGlStorageResources, IMGlStorageResourcesService> {
   	@Resource
	private MGlStorageResourcesMapper mGlStorageResourcesMapper;

    @Autowired
    private IMGlResourceStorageService glResourceStorageService;

    @Resource
    private GatewaySystemFdnServiceImpl systemFdnService;

   /**
    * 分页列表查询
    *
    * @param mGlStorageResources
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
	//@AutoLog(value = "存储设备-分页列表查询")
    @RequiresPermissions("存储设备:查询")
	@ApiOperation(value="存储设备-分页列表查询", notes="存储设备-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MGlStorageResources mGlStorageResources,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		Result<Page<MGlStorageResources>> result=new Result<>();
		Page<MGlStorageResources> pagelist = new Page(pageNo, pageSize);
        QueryWrapper<MGlStorageResources> queryWrapper = QueryGenerator.initQueryWrapper(mGlStorageResources, req.getParameterMap());
		pagelist=mGlStorageResourcesMapper.getPageList(pagelist,queryWrapper);
        List<MGlStorageResources> storageResourcesList  = pagelist.getRecords();
        List<String> ipList = new ArrayList<>();
        for (MGlStorageResources storageResources : storageResourcesList){
            if (!storageResources.getIsMonitor()){
                storageResources.setMonitorStatus(EquipmentUtils.getMonitorStatus(storageResources.getWhetherToMonitor()));
            }
            ipList.add(storageResources.getDeviceIp());
        }


        if (mGlStorageResources.getIsMonitor()){
            //查看ping返回值
            Map<String,Object> map = systemFdnService.getPingMonitor(ipList);
            for (MGlStorageResources computingResource : storageResourcesList){
                computingResource.setMonitorStatus(map.get(computingResource.getDeviceIp()).toString());
                if (computingResource.getSingleHardDiskCount().compareTo(BigDecimal.ZERO)>0 && computingResource.getUsedCapacity().compareTo(BigDecimal.ZERO)>0){
                    computingResource.setResidue(computingResource.getSingleHardDiskCount().subtract(computingResource.getUsedCapacity()));
                }
            }

        }

		result.setCode(200);
		result.setSuccess(true);
		result.setResult(pagelist);
		return result;
	}

   /**
    *   添加
    *
    * @param mGlStorageResources
    * @return
    */
   @AutoLog(value = "存储设备-添加")
   @ApiOperation(value="存储设备-添加", notes="存储设备-添加")
   @RequiresPermissions("存储设备:添加")
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody MGlStorageResources mGlStorageResources) {

       MGlStorageResources m = new MGlStorageResources();
       QueryWrapper<MGlStorageResources> queryWrapper = QueryGenerator.initQueryWrapper(m, new HashMap<>());
       queryWrapper.eq("equipment_no",mGlStorageResources.getEquipmentNo());
       if(StringUtils.isNotBlank(mGlStorageResources.getEquipmentNo())){
           if (mGlStorageResourcesMapper.selectCount(queryWrapper)>0){
               return Result.error("设备编号重复，添加失败！");
           }
       }
       mGlStorageResources.autoSetDisplayName();

       service.save(mGlStorageResources);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param mGlStorageResources
    * @return
    */
   @AutoLog(value = "存储设备-编辑")
   @ApiOperation(value="存储设备-编辑", notes="存储设备-编辑")
   @RequiresPermissions("存储设备:编辑")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
   public Result<String> edit(@RequestBody MGlStorageResources mGlStorageResources) {
       mGlStorageResources.autoSetDisplayName();
       service.edit(mGlStorageResources);
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "存储设备-通过id删除")
   @ApiOperation(value="存储设备-通过id删除", notes="存储设备-通过id删除")
   @RequiresPermissions("存储设备:删除")
   @DeleteMapping(value = "/delete")
   @Transactional(rollbackFor = Exception.class)
   public Result<String> delete(@RequestParam(name="id",required=true) String id) {
       glResourceStorageService.forceRemoveStorage(id);
       service.removeById(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "存储设备-批量删除")
   @ApiOperation(value="存储设备-批量删除", notes="存储设备-批量删除")
   @RequiresPermissions("存储设备:批量删除")
   @DeleteMapping(value = "/deleteBatch")
   @Transactional(rollbackFor = Exception.class)
   public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       List<String> idList = Arrays.asList(ids.split(","));
       glResourceStorageService.forceRemoveStorageByIds(idList);
       this.service.removeByIds(idList);
       return Result.OK("批量删除成功!");
   }

    /**
     *  监控
     *
     * @return
     */
    @AutoLog(value = "存储设备-添加监控")
    @ApiOperation(value="存储设备-添加监控", notes="存储设备-添加监控")
    @RequiresPermissions("存储设备:监控")
    @RequestMapping(value = "/monitor", method = {RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> monitor(@RequestParam(name="ids",required=true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if(idList.size()==0){
            return Result.error("数据为空!");
        }
        UpdateWrapper<MGlStorageResources> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<MGlStorageResources> lambdaUpdateWrapper = updateWrapper.lambda();
        idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlStorageResources::getId,item)));
        lambdaUpdateWrapper.set(MGlStorageResources::getWhetherToMonitor,"1");
        service.update(updateWrapper);
        return Result.OK("监控添加成功!");
    }

    /**
     *  取消监控
     *
     * @return
     */
    @AutoLog(value = "存储设备-取消监控")
    @ApiOperation(value="存储设备-取消监控", notes="存储设备-取消监控")
    @RequiresPermissions("存储设备:取消监控")
    @RequestMapping(value = "/unmonitor", method = {RequestMethod.POST})
    @Transactional(rollbackFor = Exception.class)
    public Result<String> unmonitor(@RequestParam(name="ids",required=true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if(idList.size()==0){
            return Result.error("数据为空!");
        }
        UpdateWrapper<MGlStorageResources> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<MGlStorageResources> lambdaUpdateWrapper = updateWrapper.lambda();
        idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlStorageResources::getId,item)));
        lambdaUpdateWrapper.set(MGlStorageResources::getWhetherToMonitor,"0");
        service.update(updateWrapper);
        return Result.OK("监控取消成功!");
    }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "存储设备-通过id查询")
   @ApiOperation(value="存储设备-通过id查询", notes="存储设备-通过id查询")
   @GetMapping(value = "/queryById")
   @RequiresPermissions("存储设备:查询")
   public Result<MGlStorageResources> queryById(@RequestParam(name="id",required=true) String id) {
       MGlStorageResources mGlStorageResources = service.getById(id);
       if(mGlStorageResources==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(mGlStorageResources);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param mGlStorageResources
   */
   @RequiresPermissions("存储设备:导出")
   @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
   @ApiOperation(value="存储设备-导出", notes="存储设备-导出")
   public ModelAndView exportXls(HttpServletRequest request, MGlStorageResources mGlStorageResources) {
       return super.exportXls(request, mGlStorageResources, MGlStorageResources.class, "存储设备");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequiresPermissions("存储设备:导入")
   @ApiOperation(value="存储设备-导入", notes="存储设备-导入")
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, MGlStorageResources.class);
   }

    @Override
    protected  void beforeImportExcel(List<MGlStorageResources> list){
        list.forEach(item->{
            if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getCabinet())){
                item.setCabinet(item.getCabinet().trim());
            }
            if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getMachineRoom())){
                item.setMachineRoom(item.getMachineRoom().trim());
            }
            if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getPersonLiable())){
                item.setPersonLiable(item.getPersonLiable().trim());
            }
        });
    }

    @Override
    protected void afterImportExcel(List<MGlStorageResources> list){
        UpdateWrapper<MGlStorageResources> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().isNull(MGlStorageResources::getCabinetId);
        updateWrapper.setSql("Cabinet_id=(select id from m_cabinet where Cabinet=name LIMIT 1)");
        this.service.update(updateWrapper);

        updateWrapper.clear();
        updateWrapper.lambda().isNull(MGlStorageResources::getMachineRoomId);
        updateWrapper.setSql("Machine_Room_Id=(select id from m_machine_room where machine_room=name LIMIT 1)");
        this.service.update(updateWrapper);

        updateWrapper.clear();
        updateWrapper.lambda().isNull(MGlStorageResources::getPersonLiableId);
        updateWrapper.setSql("person_liable_id=(select id from sys_user where person_liable=realname LIMIT 1)");
        this.service.update(updateWrapper);
    }

    @RequiresPermissions("存储设备:查询")
    @ApiOperation(value="存储设备-分页列表查询", notes="存储设备-分页列表查询")
    @GetMapping(value = "/analysis")
    public Result<?> analysis(MGlStorageResources mGlStorageResources,
                              HttpServletRequest req) {
        return Result.ok(service.analysis(mGlStorageResources));
    }

}
